package main

import (
	"fmt"
	"github.com/gorhill/cronexpr"
	"time"
)

type CronJob struct {
	expr     *cronexpr.Expression
	nextTime time.Time
}

// 设置定时任务，定时轮训检查所有的Cron任务, 谁过期了就执行谁
func main() {
	var (
		cronJob       *CronJob
		expr          *cronexpr.Expression
		err           error
		now           time.Time
		scheduleTable map[string]*CronJob
	)
	scheduleTable = make(map[string]*CronJob, 5)

	// 当前时间
	now = time.Now()

	if expr, err = cronexpr.Parse("*/2 * * * * * *"); err != nil {
		fmt.Println("cronexpr Parse failed: ", err)
		return
	}
	cronJob = &CronJob{
		expr:     expr,
		nextTime: expr.Next(now),
	}
	// 注册到任务列表中
	scheduleTable["job1"] = cronJob

	if expr, err = cronexpr.Parse("*/5 * * * * * *"); err != nil {
		fmt.Println("cronexpr Parse failed: ", err)
		return
	}
	cronJob = &CronJob{
		expr:     expr,
		nextTime: expr.Next(now),
	}
	scheduleTable["job2"] = cronJob

	go func() {
		var (
			now time.Time
		)
		// 定时检查一下任务调度表

		for {
			now = time.Now()
			for jobName, cronJob := range scheduleTable {
				// 判断是否过期
				if cronJob.nextTime.Before(now) || cronJob.nextTime.Equal(now) {
					// 启动一个协程, 执行这个任务
					go func(jobName string) {
						fmt.Println("执行:", jobName)
					}(jobName)
					// 计算下一次调度时间
					cronJob.nextTime = cronJob.expr.Next(now)
					fmt.Println(jobName, "下次执行时间:", cronJob.nextTime)
				}
				select {
				case <-time.NewTimer(100 * time.Millisecond).C: // 将在100毫秒可读，返回
				}
			}
		}
	}()
	time.Sleep(50 * time.Second)
}
